import { Component, ElementRef, Renderer2 } from '@angular/core';
import { ApiService } from '@core/services/http/api.service';
import { EditorOptListComponent } from '@shared/ag-grid-ext/cell-editors/edit-opt-list.component';
import { ApesField } from '@shared/ui-zorro/src/types/apes-field';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { Events } from '@core/services/events/Events';
import { SubjectService } from '@core/services/events/subject.service';
import { deepClone } from '../../../../utils/utils';
import { GridConfigService } from '@core/config/grid-config.service';
import { AllModules, Module } from '@ag-grid-enterprise/all-modules';
import { Subject } from 'rxjs/internal/Subject';

@Component({
  selector: 'formly-field-role-check-opt',
  template: `
    <div apes-col style='padding:0 !important;' [apesMd]='24'>
      <apes-form-item style='padding:0 !important;'>
        <div apes-row>
          <div apes-col [apesSpan]="3" style="justify-content: flex-start;display: flex;padding: 0.5em;">
            <button apes-button (click)="onSelectAll()">全选</button>
            <button apes-button (click)="unSelectAll()">全部取消</button>
          </div>
          <div apes-col [apesSpan]="4" style="padding:5px;">
            <apes-input-group [apesPrefix]="prefixIconSearch" [apesSuffix]="suffixIconClear">
              <input apes-input type="search"
                     style="width:100%"
                     [(ngModel)]="quickSearchInput"
                     id="filter-text-box"
                     placeholder="请输入关键字菜单搜索..."
                     (input)="onFilterTextBoxChanged()"
                     (keyup)="onFilterTextBoxChanged()"
                     (click)="onFilterTextBoxChanged()"
                     class="search-input">
            </apes-input-group>
            <ng-template #prefixIconSearch>
              <img [src]="'./assets/tmp/img/fn/search.png'"/>
            </ng-template>
            <ng-template #suffixIconClear>
              <i apes-icon apesType="close-circle" *ngIf="quickSearchInput != null && quickSearchInput != ''"
                 (click)="clearSearch()"></i>
            </ng-template>
          </div>
        </div>
        <div style="height: 560px;">
          <ag-grid-angular
            #agGrid
            style="width: 100%; height: 100%;"
            id="myGrid"
            class="ag-theme-balham"
            [columnDefs]="columnDefs"
            [rowData]="value"
            rowSelection="multiple"
            [treeData]="true"
            [localeText]="localeText"
            [modules]="modules"
            [animateRows]="false"
            [frameworkComponents]="frameworkComponents"
            [suppressRowClickSelection]="true"
            [groupDefaultExpanded]="groupDefaultExpanded"
            [getDataPath]="getDataPath"
            [autoGroupColumnDef]="autoGroupColumnDef"
            (rowClicked)="onRowClicked($event)"
            (rowSelected)="onRowSelected($event)"
            (gridReady)="onGridReady($event)"
          ></ag-grid-angular>
        </div>
      </apes-form-item>
    </div>
  `,
})

export class FormlyFieldCheckOpt extends ApesField {

  modules: Module[] = AllModules;
  metaData: any = [];
  value: any = [];
  select: any = [];
  columnDefs: any;
  gridApi;
  gridColumnApi;
  frameworkComponents;
  groupDefaultExpanded;
  getDataPath;
  autoGroupColumnDef;
  localeText: any;
  private selectStatus = true;
  private checkOptList = [];
  private enable = false;

  constructor(protected apiService: ApiService,
              protected events: Events,
              protected expressionService: ExpressionService,
              protected elementRef: ElementRef,
              protected renderer: Renderer2,
              protected subjectService: SubjectService,
              protected gridConfigService: GridConfigService,
  ) {
    super(apiService, events, expressionService, subjectService);
    this.localeText = gridConfigService.getLocaleText();
    this.columnDefs = [
      {
        field: 'operations',
        headerName: '操作',
        cellRenderer: 'EditorOptList',
        width: 850,
        editable: false,
        disabled: true,
      },
      { field: 'id', hide: true },
      { field: 'name', hide: true },
      {
        field: 'terminal.description',
        headerName: '终端',
        filter: true,
      }];

    this.frameworkComponents = {
      EditorOptList: EditorOptListComponent,
    };
    this.groupDefaultExpanded = 0;
    this.getDataPath = (data) => {
      return data.path.split('/');
    };
    this.autoGroupColumnDef = {
      headerName: '菜单',
      resizable: true,
      cellRendererParams: {
        innerRenderer: (params) => {
          return params.data.name;
        },
        checkbox: (params) => {
          return params.node.data.hasOwnProperty('operations') === true && this.enable;
        },
      },
    };
    this.searchSubject.pipe().subscribe((data) => {
      if(data){
        this.gridApi.expandAll();
      } else {
        this.gridApi.collapseAll();
      }
      this.gridApi.setQuickFilter(data);
    });
  }

  onGridReady(params) {
    this.gridApi = params.api;
    this.gridColumnApi = params.columnApi;

    params.api.sizeColumnsToFit();
  }

  ngOnInit(): void {
    let data = { 'terminalTypeId': this.to['postData'] };
    this.apiService.post('aut.menu.getTreePath', { 'body': JSON.stringify(data) }).subscribe(
      (body) => {
        if (body) {
          this.value = body;
          this.metaData = body;
        }
      });
    this.subject.subscribe(this.formState, this.subject.event_form_button, data => {
      let disabled = this.formState.states == 'submit' ? false : true;
      this.enable = !disabled;
      this.columnDefs = [{
        field: 'operations',
        headerName: '操作',
        cellRenderer: 'EditorOptList',
        width: 850,
        resizable: true,
        editable: false,
        disabled: disabled,
      },
        { field: 'id', hide: true }, { field: 'name', hide: true }, {
          field: 'terminal.description',
          headerName: '终端',
          filter: true,
        }];
      if (data.action == 'action_submit') {
        this.patchValue();
      }
      let fieldValue = this.model[this.key] ? this.model[this.key] : [];
      this.checkNodeOpt(fieldValue);
    });

  }

  checkNodeOpt(params) {
    this.gridApi.forEachNode(node => {
        if (node.data.hasOwnProperty('operations')) {
          let menu_id = node.data['id'];
          let menuOpt = this.getOpts(params, menu_id);
          if (node.data.operations.length == menuOpt.length) {
            node.setSelected(true);
          } else {
            node.setSelected(false);
          }
          node.data.operations.forEach(opt => {
            opt.checked = false;
            menuOpt.forEach(item => {
              if (opt['operationId'] == item['operationId']) {
                opt.checked = true;
              }
            });
          });
        } else {
          node.expanded = false;
        }
      },
    );
  }

  getOpts(params, menu_id) {
    let checkOpts = [];
    params.forEach(item => {
      if (item['menu_id'] == menu_id) {
        checkOpts.push(item);
      }
    });
    return checkOpts;
  }

  test() {
    console.log(this.model);
    console.log(this.value);
    this.groupDefaultExpanded = 0;
  }

  onSelectAll() {
    this.gridApi.forEachNode(node => {
      if (node.data.hasOwnProperty('operations')) {
        node.setSelected(true);
        node.data.operations.forEach(item => item.checked = true);
      }
    });
    this.groupDefaultExpanded = -1;
  }

  unSelectAll() {
    this.gridApi.forEachNode(node => {
      if (node.data.hasOwnProperty('operations')) {
        node.setSelected(false);
        node.data.operations.forEach(item => item.checked = false);
      }
    });
    this.groupDefaultExpanded = -1;
  }

  onRowSelected(params) {
    //克隆值
    const tempList = deepClone(params.node.data.operations);
    //改变node里面按钮值为勾选的状态
    params.node.data.operations.forEach(item => item.checked = params.node.selected);
    //记录是否重新计算 checkOptList  注 点击勾选框无法触发onRowClicked
    let flag = true;
    //计算是否 所有按钮为true并且selected为false
    let count = 0;
    tempList.forEach(opt => {
      if (opt['checked'] == true && params.node.selected == false) {
        count++;
      }
    });
    if (count == tempList.length) {
      flag = false;
    }
    if (flag) {
      if (params.data.hasOwnProperty('operations')) {
        let checkOpt = [];
        tempList.forEach(item => {
          if (item.checked) {
            checkOpt.push(item);
          }
        });
        this.checkOptList = deepClone(checkOpt);
      }
    }

    params.node.data.operations.forEach(opt => {
      this.checkOptList.forEach(item => {
        if (opt['operationId'] == item['operationId'] && item['checked'] == true) {
          opt.checked = true;
        }
      });
    });
    this.checkOptList = [];
    this.patchValue();
  }

  patchValue() {
    let returnData = [];
    this.value.forEach(menu => {
      if (menu.hasOwnProperty('operations')) {
        let operations = menu['operations'];
        operations.forEach(opt => {
          if (opt.checked) {
            returnData.push(opt);
          }
        });
      }
    });
    this.formControl.patchValue(returnData);
    this.model[this.key] = returnData;
  }

  onRowClicked(params) {
    console.log('onRowClicked------------');
    console.log(params);
    if (params.data.hasOwnProperty('operations')) {
      let checkOpt = [];
      params.data.operations.forEach(item => {
          if (item.checked == false) {
            this.selectStatus = false;
          }
          checkOpt.push(item);
        },
      );
      if (this.selectStatus) {
        params.node.setSelected(true);
      } else {
        this.checkOptList = deepClone(checkOpt);

        params.node.setSelected(false);

        this.selectStatus = true;
      }

    }
    this.patchValue();
  }

  private searchSubject = new Subject<string>();
  quickSearchInput: any;

  onFilterTextBoxChanged() {
    let data = this.quickSearchInput;
    this.searchSubject.next(data);
  }

  clearSearch() {
    this.quickSearchInput = '';
    this.onFilterTextBoxChanged();
  }
}
